﻿using MengLin.OOP.DesignPattern.WMS_LC.Interface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace MengLin.OOP.DesignPattern.WMS_LC.Scheduler.Implements
{
    /// <summary>
    /// 调度器
    /// 版本3调度器做了1件事
    /// 1.进行调度
    /// </summary>
    public class AlarmClock: AbstractScheduler
    {
        /// <summary>
        /// 容器
        /// </summary>
        private static Dictionary<int, IAlarmListener> _container;
        private DateTime dt = DateTime.Now;

        /// <summary>
        /// 注册警报侦听器
        /// </summary>
        /// <param name="interval"></param>
        /// <param name="alarmListener"></param>
        public static void WakeEvery(int interval, IAlarmListener alarmListener)
        {
            if (_container == null)
            {
                _container = new Dictionary<int, IAlarmListener>();
                _container.Add(interval, alarmListener);
            }
            else
            {
                _container.Add(interval, alarmListener);
            }
        }

        /// <summary>
        /// 轮询
        /// </summary>
        public override void Tic()
        {
            Task.Run(() =>
            {
                while (true)
                {
                    foreach (var item in _container)
                    {
                        DateTime now = DateTime.Now;
                        TimeSpan timeSpan = now.Subtract(dt).Duration();
                        if (timeSpan.Seconds >= item.Key)
                        {
                            //Wakeup
                            item.Value.Wakeup();
                        }
                    }
                    Thread.Sleep(2000);
                }
            });
        }
    }
}
